package org.devops


//代码扫描 不使用插件
def SonarScan(){
    withCredentials([usernamePassword(credentialsId: 'sonar-admin', 
														passwordVariable: 'SONAR_PASSWD', 
														usernameVariable: 'SONAR_USER')]) {
        sh """
            sonar-scanner \
            -Dsonar.login=${SONAR_USER} \
            -Dsonar.password=${SONAR_PASSWD} \
            -Dsonar.host.url=http://sonar.idevops.site 
        """
    }
}

//代码扫描 使用插件
def SonarScanPlugin(){
    // sonar plugin
    withSonarQubeEnv(credentialsId: '909c14d6-f364-4811-bb13-60f8f6566ecf') {
        sh """sonar-scanner \
            -Dsonar.login=${SONAR_AUTH_TOKEN} \
            -Dsonar.projectVersion=${env.branchName} \
            -Dsonar.branch.name=${env.branchName}
        """
    }
}

def SonarRequest(apiUrl,method){
    withCredentials([usernamePassword(credentialsId: 'sonar-admin', 
														passwordVariable: 'SONAR_PASSWD', 
														usernameVariable: 'SONAR_USER')]) {
        sonarApi = "http://sonar.idevops.site/api"
        response = sh  returnStdout: true, 
            script: """
            curl --location \
                 --request ${method} \
                 "${sonarApi}/${apiUrl}" \
                 -u ${SONAR_USER}:${SONAR_PASSWD}
            """
        println(response)
        try {
            response = readJSON text: """ ${response - "\n"} """
        } catch(e){
            response = readJSON text: """{"errors" : true}"""
        }
        return response
        
    }
}

// 更新质量阈
def UpdateQualityProfiles(lang, projectName, profileName){
    apiUrl = "qualityprofiles/add_project?language=${lang}&project=${projectName}&qualityProfile=${profileName}"
    response = SonarRequest(apiUrl,"POST")
    
    if (response.errors != true){
        println("ERROR: UpdateQualityProfiles ${response.errors}...")
        return false
    } else {
        println("SUCCESS: UpdateQualityProfiles ${lang} > ${projectName} > ${profileName}" )
        return true
    }
}

// 创建项目
def CreateProject(projectName){
    apiUrl = "projects/create?name=${projectName}&project=${projectName}"
    response = SonarRequest(apiUrl,"POST")
    try{
        if (response.project.key == projectName ) {
            println("Project Create success!...")
            return true
        }
    }catch(e){
        println(response.errors)
        return false
    }
}

// 查找项目
def ProjectSearch(projectName){
    apiUrl = "projects/search?projects=${projectName}"
    response = SonarRequest(apiUrl,"GET")

    if (response.paging.total == 0){
        println("Project not found!.....")
        return false
    } 
    return true
}